<template>
  <div class="edit-course-container">
    <el-page-header @back="goBack" content="编辑课程" />
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-position="top"
      >
        <el-form-item label="课程名称" prop="cou_name">
          <el-input 
            v-model="form.cou_name" 
            placeholder="请输入课程名称" 
            clearable 
          />
        </el-form-item>
        
        <el-form-item label="课程简介">
          <el-input
            v-model="form.cou_introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入课程简介"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="课程封面">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.cou_pic" :src="form.cou_pic" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="课程价格">
          <el-input-number 
            v-model="form.cou_price" 
            :min="0" 
            :precision="2" 
            :step="10"
            placeholder="请输入课程价格"
          />
          <span class="price-unit">元</span>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { teacherApi } from '@/api/teacher'

const router = useRouter()
const route = useRoute()
const courseId = route.params.id

const formRef = ref()
const form = reactive({
  cou_name: '',
  cou_introduction: '',
  cou_pic: '',
  cou_price: 0
})

const rules = {
  cou_name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 获取课程详情
const fetchCourseDetail = async () => {
  try {
    const response = await teacherApi.getCourseDetail(courseId)
    Object.assign(form, response.data)
  } catch (error) {
    ElMessage.error('获取课程详情失败: ' + error.message)
    router.go(-1)
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 图片上传成功
const handleAvatarSuccess = (response) => {
  form.cou_pic = response.data.url
}

// 图片上传前校验
const beforeAvatarUpload = (file) => {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGorPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPGorPNG && isLt2M
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    // 构建更新数据
    const updateData = {
      id: courseId,
      ...form
    }
    
    // 调用API更新课程
    const response = await teacherApi.updateCourse(updateData)
    
    ElMessage.success('课程更新成功')
    router.push('/teacher/courses')
  } catch (error) {
    console.error('更新课程失败:', error)
    ElMessage.error('更新课程失败: ' + (error.response?.data?.message || error.message))
  }
}

// 重置表单
const resetForm = () => {
  fetchCourseDetail()
}

// 初始化加载数据
onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.edit-course-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  margin-top: 20px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.price-unit {
  margin-left: 10px;
  color: #666;
}
</style>